<template>
  <div class="statistics-container">
    <h1>统计分析</h1>

    <!-- 图表布局容器 -->
    <div class="chart-layout">
      <!-- 柱状图容器 -->
      <div class="chart-item">
        <h3>分类数量统计</h3>
        <div class="chart-box bar-chart" style="height: 400px;"></div>
      </div>

      <!-- 饼图容器 -->
      <div class="chart-item">
        <h3>分类占比统计</h3>
        <div class="chart-box pie-chart" style="height: 400px;"></div>
      </div>
    </div>

    <!-- 分类详情弹窗 -->
    <el-dialog title="分类详情" :visible.sync="dialogVisible" width="700px" append-to-body>
      <div class="category-detail">
        <h3>{{ currentCategory.name }}（共 {{ currentCategory.count }} 条）</h3>

        <!-- 表格形式展示数据 -->
        <el-table
          v-if="currentCategory.items.length > 0"
          :data="currentCategory.items"
          border
          stripe
          style="width: 100%; margin-top: 15px;"
        >
          <el-table-column type="index" label="项目" width="80" align="center" />
          <el-table-column prop="description" label="描述" align="left">
            <template slot-scope="scope">
              {{ scope.row.description || '无描述' }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="left">
            <template slot-scope="scope">
              {{ scope.row.remark || '无备注' }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 无数据时显示 -->
        <div v-else class="no-data">
          该分类下无项目数据
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.statistics-container {
  padding: 20px;
}

.chart-layout {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.chart-item {
  flex: 1;
  min-width: 300px;
}

.chart-item h3 {
  text-align: center;
  margin-bottom: 15px;
  color: #666;
}

.chart-box {
  width: 100%;
  height: 100%;
}

.category-detail {
  padding: 10px;
  line-height: 1.6;

  h3 {
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
    margin-bottom: 15px;
  }

  .no-data {
    text-align: center;
    padding: 20px;
    color: #999;
  }
}
</style>

<script>
import * as echarts from 'echarts';
import { listCat } from "@/api/cf/cat";

export default {
  name: "Statistics",
  data() {
    return {
      // 图表实例
      barChartInstance: null,
      pieChartInstance: null,
      // 数据相关
      categoryData: [],
      categoryDetailMap: {},
      totalCount: 0,
      // 弹窗相关
      dialogVisible: false,
      currentCategory: {
        name: '',
        count: 0,
        items: []
      }
    };
  },
  mounted() {
    this.initCharts();
    this.fetchCategoryData();
  },
  beforeUnmount() {
    this.destroyCharts();
  },
  methods: {
    // 初始化图表
    initCharts() {
      // 柱状图
      const barDom = document.querySelector('.bar-chart');
      this.barChartInstance = echarts.init(barDom);

      // 饼图
      const pieDom = document.querySelector('.pie-chart');
      this.pieChartInstance = echarts.init(pieDom);

      // 窗口resize事件
      window.addEventListener('resize', () => {
        this.barChartInstance?.resize();
        this.pieChartInstance?.resize();
      });
    },

    // 销毁图表
    destroyCharts() {
      this.barChartInstance?.dispose();
      this.pieChartInstance?.dispose();
    },

    // 获取分类数据
    fetchCategoryData() {
      listCat({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.categoryData = res.rows;
        this.updateCharts();
      }).catch(err => {
        console.error("数据获取失败:", err);
        this.$message.error("加载数据失败，请刷新页面重试");
      });
    },

    // 更新图表数据
    updateCharts() {
      const { names, counts, detailMap } = this.aggregateData();
      this.categoryDetailMap = detailMap;
      this.totalCount = counts.reduce((a, b) => a + b, 0);

      this.renderBarChart(names, counts);
      this.renderPieChart(names, counts);
      this.bindBarChartClick(names, counts);
    },

    // 数据聚合处理
    aggregateData() {
      const countMap = {};
      const detailMap = {};

      this.categoryData.forEach(item => {
        const name = item.category_name || '未命名分类';
        countMap[name] = (countMap[name] || 0) + 1;
        if (!detailMap[name]) detailMap[name] = [];
        detailMap[name].push({
          description: item.description,
          remark: item.remark
        });
      });

      return {
        names: Object.keys(countMap),
        counts: Object.values(countMap),
        detailMap
      };
    },

    // 渲染柱状图
    renderBarChart(names, counts) {
      this.barChartInstance.setOption({
        title: { text: '', left: 'center' },
        tooltip: { trigger: 'axis', formatter: '{b}: {c} 条' },
        grid: { left: '5%', right: '5%', bottom: '15%', containLabel: true },
        xAxis: {
          type: 'category',
          data: names,
          axisLabel: { rotate: 45, interval: 0 }
        },
        yAxis: { type: 'value', name: '数量', minInterval: 1 },
        series: [{
          name: '分类数量',
          type: 'bar',
          data: counts,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#3fb1e3' },
              { offset: 1, color: '#6be6c1' }
            ])
          }
        }]
      });
    },

    // 渲染饼图（含动态占比计算）
    renderPieChart(names, counts) {
      // 1. 基础数据（不含静态占比）
      const pieData = names.map((name, i) => ({ name, value: counts[i] }));

      // 2. 饼图配置
      this.pieChartInstance.setOption({
        tooltip: {
          trigger: 'item',
          formatter: params => {
            const visibleData = this.getVisibleData();
            const total = visibleData.reduce((sum, item) => sum + item.value, 0);
            const percent = total > 0 ? ((params.value / total) * 100).toFixed(1) : 0;
            return `${params.name}: ${params.value} 条 (${percent}%)`;
          }
        },
        legend: {
          orient: 'vertical',
          left: 10,
          formatter: name => {
            const visibleData = this.getVisibleData();
            const total = visibleData.reduce((sum, item) => sum + item.value, 0);
            const item = visibleData.find(item => item.name === name);
            const percent = total > 0 && item ? ((item.value / total) * 100).toFixed(1) + '%' : '0%';
            return `${name} (${percent})`;
          }
        },
        series: [{
          name: '分类占比',
          type: 'pie',
          radius: ['40%', '70%'],
          data: pieData,
          stillShowZeroSum: false, // 隐藏取消选择的分类
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          }
        }]
      });

      // 3. 监听图例选择事件，动态更新占比
      this.pieChartInstance.off('legendselectchanged'); // 移除旧监听避免重复触发
      this.pieChartInstance.on('legendselectchanged', () => {
        this.pieChartInstance.setOption(this.pieChartInstance.getOption()); // 刷新图表
      });
    },

    // 获取当前可见数据（根据图例选择状态）
    getVisibleData() {
      const option = this.pieChartInstance.getOption();
      const legendSelected = option.legend[0]?.selected || {}; // 图例选择状态
      const pieData = option.series[0]?.data || []; // 原始数据

      // 筛选可见数据（未显式取消选择的视为可见）
      return pieData.filter(item => legendSelected[item.name] !== false);
    },

    // 绑定柱状图点击事件
    bindBarChartClick(names, counts) {
      this.barChartInstance.on('click', params => {
        const name = names[params.dataIndex];
        this.currentCategory = {
          name,
          count: counts[params.dataIndex],
          items: this.categoryDetailMap[name] || []
        };
        this.dialogVisible = true;
      });
    }
  }
};
</script>
